#!/bin/bash -
#===============================================================================
#
#          File: a.sh
#
#         Usage: ./git-update-dirs
#
#   Description: 
#
#       Options: ---
#  Requirements: ---
#          Bugs: ---
#         Notes: ---
#        Author: ShadowStar, <orphen.leiliu@gmail.com>
#  Organization: Gmail
#       Created: 05/06/14 17:48:00
#   Last Change: 04/12/2019 21:07:57
#      Revision:  ---
#===============================================================================

set -o nounset                              # Treat unset variables as an error

export LC_ALL=en_US.UTF-8

DIR=$PWD

usage () {
	echo "Usage: $0 [<git work-tree/repository>]"
	echo "       <git work-tree/repository>  -- work-tree or repository which to be updated, default \$PWD"
	exit -1
}

[ $# -le 1 ] || usage

until [ $# -eq 0 ]; do
	case "$1" in
		-*)
			usage ;;
		*)
			DIR="$(realpath $1)";
			shift ;;
	esac
done

if [[ ! -e $(which git) ]]; then
	echo "Command \`\`git'' NOT found"
	exit -1
fi

if [[ -e ${DIR}/.git ]]; then
	gitarg="--git-dir=\"${DIR}/.git\" --work-tree=\"${DIR}\""
else
	gitarg="--git-dir=\"${DIR}\""
fi

check () {
	eval git ${gitarg} remote >/dev/null 2>&1 || \
	(echo "Can't NOT fetch remote for [${DIR}], or it isn't a git work-tree/repository." >&2; return -1)
}

check || exit -1

eval git ${gitarg} remote update && eval git ${gitarg} remote prune origin

ret=$?
LC_ALL=C date > "${DIR}"/.lastupdate
eval git ${gitarg} gc --quiet
exit $ret
